<template>
  <my-container>
    <template #header>
      <!-- <el-form
        class="ad-form-query"
        :inline="true"
      >
        <el-form-item>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="editModel"
          >导出</el-button>
        </el-form-item>
      </el-form> -->

      <div ref="gantt" class="left-container" />
      <el-row style="padding: 6px 0 ">
        <el-col :span="6" class="toolbar roles">
          <transition name="fade-transform" mode="out-in">
            <el-card v-if="showTskDetail">
              <template #header>
                <div class="clearfix">
                  <span style="font-size: 16px;">{{ taskModel.tittle }}</span>
                  <el-button style="float: right; padding: 3px 0" type="text" class="button" @click="checkMsg()">查看日志</el-button>
                </div>
              </template>
              <div style="padding: 14px;">
                <el-row>
                  <el-col :span="18">
                    <div>
                      <span style="display:inline-block;padding:2px 0; font-size: 16px;">责任人：</span>
                      <span style="display:inline-block; font-size: 16px;">{{ taskModel.responName }}</span>
                    </div>

                    <div>
                      <span style="display:inline-block; padding:2px 0; font-size: 16px;">开始时间：</span>
                      <span style="display:inline-block; font-size: 16px;">{{ taskModel.start_date }}</span>
                    </div>
                    <div>
                      <span style="display:inline-block;padding:2px 0; font-size: 16px;">预计结束时间：</span>
                      <span style="display:inline-block; font-size: 16px;">{{ taskModel.end_date }}</span>
                    </div>
                    <div>
                      <span style="display:inline-block;padding:2px 0; font-size: 16px;">备注：</span>
                      <span style="display:inline-block; font-size: 16px;">{{ taskModel.remark }}</span>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <span style="display:inline-block;padding:2px 0; font-size: 16px;">当前进度：</span>
                    </div>
                    <div>
                      <el-progress type="circle" :color="customColorMethod" :percentage="taskModel.progress*100" />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
            <el-card v-if="showTsksj">
              <template #header>
                <div class="clearfix">
                  <span style="font-size: 16px;">{{ taskModel.tittle }}</span>
                </div>
              </template>
              <div style="padding: 14px;">
                <row>
                  <div>
                    <span style="display:inline-block;padding:3px 0; font-size: 16px;">责任人：</span>
                    <span style="display:inline-block; font-size: 16px;">{{ taskModel.responName }}</span>
                  </div>
                </row>
                <div>
                  <span style="display:inline-block; padding:3px 0; font-size: 16px;">计划开始时间：</span>
                  <span style="display:inline-block; font-size: 16px;">{{ taskModel.start_date }}</span>
                </div>
                <div>
                  <span style="display:inline-block;padding:3px 0; font-size: 16px;">计划结束时间：</span>
                  <span style="display:inline-block; font-size: 16px;">{{ taskModel.end_date }}</span>
                </div>
                <div>
                  <span style="display:inline-block;padding:3px 0; font-size: 16px;">备注：</span>
                  <span style="display:inline-block; font-size: 16px;">{{ taskModel.remark }}</span>
                </div>
              </div>
            </el-card>
          </transition>
        </el-col>
        <el-col style="padding: 0 13px " :span="18" class="toolbar perms">
          <transition name="fade-transform" mode="out-in">
            <el-card v-if="showTskHis">
              <template #header>
                <div class="clearfix">
                  <span style="font-size: 16px;">日志</span>
                </div>
              </template>
              <vxe-grid
                ref="xGrid"
                border
                resizable
                stripe
                auto-resize
                show-overflow
                size="small"
                :proxy-config="proxyConfig"
                :loading="listLoading"
                :columns="tableColumn"
              >
                <template v-slot:progress-his="{ row}">
                  <el-progress :percentage="row.progress" :color="customColor" />
                </template>
                <template v-slot:operate="{$index, row }">
                  <vxe-button v-if="row.filePath!==null" icon="fa fa-download" title="附件下载" circle @click="download($index,row)" />
                </template>
              </vxe-grid>
            </el-card>
          </transition>
        </el-col>
      </el-row>
    </template>
  </my-container>
</template>

<script>
import gantt from 'dhtmlx-gantt' // 引入模块
import moment from 'moment'
import XEUtils from 'xe-utils'
import { getGanttData
} from '@/api/project/project'
import { getTaskHisPage } from '@/api/project/taskrun'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_marker.js'
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_tooltip.js'
import 'dhtmlx-gantt/codebase/locale/locale_cn' // 本地化
import MyContainer from '@/components/my-container'
export default {
  name: 'Gantt',
  components: { MyContainer },
  filters: {
    toPercent(val) {
      if (!val) {
        return '0'
      }
      return Math.round((+val) * 100)
    },
    niceDate(obj) {
      return `${obj.getFullYear()} / ${obj.getMonth() + 1} / ${obj.getDate()}`
    }
  },
  props: {
    projectid: {
      type: Number,
      default: 0
    }
  },
  // components: { Gantt },
  data() {
    return {
      pId: this.projectid,
      events: [],
      filter: {
        id: 0
      },
      listLoading: false,
      currtaskId: null,
      showTskHis: false,
      showTsksj: false,
      showTskDetail: false,
      tasks: {
        data: [
        ]
      },
      selectedTask: null,
      messages: [],
      proxyConfig: {
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）
          query: async({ page, sort, filters, form }) => {
            // 处理排序条件
            const para = {
              currentPage: 1, // page.currentPage
              pageSize: 1, // page.pageSize
              filter: this.filter
            }
            this.listLoading = true
            const res = await getTaskHisPage(para)
            this.listLoading = false

            if (!res?.success) {
              return
            }
            return res.data.result
          }
        }
      },
      tableColumn: [
        { field: 'createdTime', title: '更新时间', formatter: this.formatDate },
        { field: 'remark', title: '备注' },
        { field: 'progress', title: '进度', slots: {
        // 对应自定义插槽的名称
          default: 'progress-his'
        }},
        { field: 'actorName', title: '操作人' },
        { title: '附件', width: 100, fixed: 'right', slots: { default: 'operate' }}
      ],
      taskModel: { tittle: '', responName: '', start_date: null, end_date: null, progress: 0, remark: ''
      }
    }
  },
  watch: {
    projectid(newValue, oldValue) {
      this.loadData(newValue)
    }
  },
  created() {
    console.log('des')
    this.ganttEvents().destroy()
    gantt.clearAll() // 先清空，再添加，就不会有缓存
  },
  mounted: function() {
    var element = document.createElement('script')
    element.src = 'http://export.dhtmlx.com/gantt/api.js'
    document.body.appendChild(element)
    // this._initGanttEvents()
    gantt.config.columns = [
      { name: 'text', label: '项目', tree: true, min_width: 180, width: 200, resize: true },
      { name: 'start_date', label: '开始时间', align: 'center', width: 100, resize: true },
      { name: 'end_date', label: '结束时间', align: 'center', width: 100, resize: true },
      { name: 'personName', label: '负责人', align: 'center' }
    ]
    gantt.config.row_height = 21
    gantt.config.scale_unit = 'month'
    gantt.config.scale_height = 65
    gantt.config.date_scale = '%Y年 %M'
    gantt.config.min_column_width = 31
    gantt.config.show_progress = true
    gantt.config.prevent_default_scroll = false
    gantt.config.grid_width = 245
    gantt.config.show_task_cells = false
    gantt.config.show_marker = true
    gantt.config.grid_resize = false
    gantt.config.smart_scales = true
    gantt.config.subscales = [
      { unit: 'week', step: 1, date: '第 %W 周' },
      {
        unit: 'day',
        step: 1,
        date: '%j',
        css: (date) => {
          let subClassName = 'sub_scale'
          if (date.getDay() === 6 || date.getDay() === 0) subClassName += ' weekend'
          return subClassName
        }
      }
    ]
    gantt.config.drag_links = false
    gantt.config.details_on_dblclick = false
    // 只读模式
    gantt.config.readonly = true
    // gantt.templates.task_cell_class = (item, date) => {
    //   if (date.getDay() === 6 || date.getDay() === 0) {
    //     return 'weekend'
    //   }
    //   return false
    // }
    // gantt.ignore_time = (date) => {
    //   if (date.getDay() === 0 || date.getDay() === 6) {
    //     return this.hideWeekend
    //   }
    //   return false
    // }
    // gantt.config.task_height = 20
    // gantt.config.row_height = 25
    // gantt.config.subscales = [
    //   { unit: 'month', step: 1, date: ' %Y年%n月' }
    // ]
    // gantt.config.date_scale = ' %d日'
    // gantt.config.scale_unit = 'day'
    // gantt.config.min_column_width = 30

    gantt.config.layout = {
      css: 'gantt_container',
      cols: [
        {
          width: 400,
          min_width: 300,
          rows: [
            { view: 'grid', scrollX: 'gridScroll', scrollable: true, scrollY: 'scrollVer' },
            { view: 'scrollbar', id: 'gridScroll', group: 'horizontal' }
          ]
        },
        { resizer: true, width: 1 },
        {
          rows: [
            { view: 'timeline', scrollX: 'scrollHor', scrollY: 'scrollVer' },
            { view: 'scrollbar', id: 'scrollHor', group: 'horizontal' }
          ]
        },
        { view: 'scrollbar', id: 'scrollVer' }
      ]
    }

    gantt.config.wide_form = 1

    gantt.templates.task_class = function(st, end, item) {
      return item.$level === 0 ? 'gantt_project' : item.$level === 1 ? '' : (item.warn === true ? 'warning' : 'completed_task')
    }
    this.loadData(this.pId)

    const today = moment()
      .hour(12)
      .minute(0)
      .second(0)
      .toDate()
    //        console.log(today)moment().format('LL')
    //        var today = new Date(2013, 3, 5)
    gantt.addMarker({
      start_date: today,
      css: 'today',
      text: '今天',
      title: `今天： ${moment(today).format('YYYY-MM-DD')}`
    })
    gantt.renderMarkers()

    gantt.attachEvent('onTaskSelected', (id) => {
      if (this.currtaskId !== id) {
        this.currtaskId = id
        for (var i = 0; i < this.tasks.data.length; i++) {
          if (this.tasks.data[i].id == this.currtaskId) {
            if (this.tasks.data[i].text === '实际进度') {
              var task = this.getTask(this.tasks.data[i].parent)
              this.taskModel.tittle = task.text + '--实际进度'
              this.taskModel.responName = task.personName
              this.taskModel.start_date = this.changeDate(this.tasks.data[i].start_date)
              this.taskModel.end_date = this.changeDate(this.tasks.data[i].end_date)
              this.taskModel.progress = this.tasks.data[i].progress
              this.filter.id = this.tasks.data[i].parent
              this.taskModel.remark = task.remark
              this.showTsksj = false
              this.showTskDetail = true
              this.showTskHis = false
            } else {
              if (this.tasks.data[i].parent != 0) {
                this.taskModel.tittle = this.tasks.data[i].text + '--计划'
                this.taskModel.responName = this.tasks.data[i].personName
                this.taskModel.start_date = this.changeDate(this.tasks.data[i].start_date)
                this.taskModel.end_date = this.changeDate(this.tasks.data[i].end_date)
                this.showTsksj = true
                this.taskModel.remark = this.tasks.data[i].remark
                this.showTskDetail = false
                this.showTskHis = false
              } else {
                this.showTskDetail = false
                this.showTsksj = false
                this.showTskHis = false
              }
            }
            console.log(this.tasks.data[i].id + '\n')
          }
        }
      }
    })

    gantt.attachEvent('onTaskIdChange', (oldid, id) => {
      if (this.currtaskId !== id) {
        this.currtaskId = id
        for (var i = 0; i < this.tasks.data.length; i++) {
          if (this.tasks.data[i].id == this.currtaskId) {
            if (this.tasks.data[i].text === '实际进度') {
              var task = this.getTask(this.tasks.data[i].parent)
              this.taskModel.tittle = task.text + '--实际进度'
              this.taskModel.responName = task.personName
              this.taskModel.start_date = this.changeDate(this.tasks.data[i].start_date)
              this.taskModel.end_date = this.changeDate(this.tasks.data[i].end_date)
              this.taskModel.progress = this.tasks.data[i].progress
              this.filter.id = this.tasks.data[i].parent
              this.taskModel.remark = task.remark
              this.showTsksj = false
              this.showTskDetail = true
              this.showTskHis = false
            } else {
              if (this.tasks.data[i].parent != 0) {
                this.taskModel.tittle = this.tasks.data[i].text + '--计划'
                this.taskModel.responName = this.tasks.data[i].personName
                this.taskModel.start_date = this.changeDate(this.tasks.data[i].start_date)
                this.taskModel.end_date = this.changeDate(this.tasks.data[i].end_date)
                this.showTsksj = true
                this.taskModel.remark = this.tasks.data[i].remark
                this.showTskDetail = false
                this.showTskHis = false
              } else {
                this.showTskDetail = false
                this.showTsksj = false
                this.showTskHis = false
              }
            }
            console.log(this.tasks.data[i].id + '\n')
          }
        }
      }
    })
  },
  methods: {
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    // formatDate(cellValue) {
    //   return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    // },
    changeDate(str) {
      var reg = /(\d{2})\-(\d{2})\-(\d{4})/
      var dtstr = str.replace(reg, '$3-$2-$1')
      return dtstr
    },
    getTask(id) {
      for (var i = 0; i < this.tasks.data.length; i++) {
        if (this.tasks.data[i].id == id) {
          return this.tasks.data[i]
        }
      }
    },
    ganttEvents() {
      return {
        on: (event, handle) => {
          const eventName = gantt.attachEvent(event, handle)
          this.events.push(eventName)
        },
        destroy: () => {
          this.events.forEach((event) => {
            gantt.detachEvent(event)
          })
          this.events = []
        }
      }
    },
    async loadData(id) {
      var rs = await getGanttData({ id: this.pId })
      this.tasks.data = rs.data
      gantt.init(this.$refs.gantt)
      // 数据解析
      gantt.parse(this.tasks)
    },
    selectTask(task) {
      this.selectedTask = task
    },
    addMessage(message) {
      this.messages.unshift(message)
      if (this.messages.length > 40) {
        this.messages.pop()
      }
    },
    download(index, row) {
      const a = document.createElement('a')
      a.href = row.filePath
      a.download = row.fileName
      a.click()
    },
    editModel() {
      gantt.exportToPDF({ header: '<style> .completed_task {border: 1px solid #94AD94;} .gantt_task_line .gantt_task_progress { background: #ACCAAC;}  .completed_task .warning { background: #ACCAAC;} .gantt_task_line.completed_task {background: #885d88;} .gantt_task_line.warning { background: #ff3b3b;} .left-container { height: 700px;}</style>', raw: true })
      // this.modalShow = !this.modalShow
    },
    logTaskUpdate(id, mode, task) {
      const text = (task && task.text ? ` (${task.text})` : '')
      const message = `Task ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
    checkMsg() {
      this.showTskHis = true
    },
    logLinkUpdate(id, mode, link) {
      let message = `Link ${mode}: ${id}`
      if (link) {
        message += ` ( source: ${link.source}, target: ${link.target} )`
      }
      this.addMessage(message)
    }
  }
}
</script>

<style scoped>
.role-item {
  font-size: 14px;
  cursor: pointer;
  padding: 10px;
}

.role-item.active {
  background: #ebf5ff;
}

.role-item:hover {
  background: #ebf5ff;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.save >>> [_button] {
  padding: 3px 0px;
}
</style>

<style>

.completed_task {
border: 1px solid #94AD94;
}

.gantt_task_line .gantt_task_progress {
background: #ACCAAC;
}

.completed_task .warning {
background: #ACCAAC;
}

.gantt_task_line.completed_task {
background: #885d88;
}
.gantt_task_line.warning {
background: #ff3b3b;
}
  .left-container {
    height: 600px;
  }
</style>
